import pandas as pd
import re
import time
import os
import shutil
from pick_utils import ReMatchFunc, str_plus
from split_utils import special_split, rule_list_1


'''
提取“拆分后元数据内容”到对应字段
'''

def pick_1(operate_dir):
    # 读取配置文件 --------------------------------------
    # 只有功能1读取“原题名”存入“拆分后元数据内容”，其他程序都是读取“拆分后元数据内容”存入“拆分后元数据内容”
    source_title_col = '拆分后元数据内容'
    # -------------------------------------------------

    # 检测excel数量，只能放一个，当只有一个excel时，提取它的路径excel_path -------
    print('检查路径下的文件格式...')
    excel_name = None
    excel_count = 0
    file_list = os.listdir(operate_dir)
    for file in file_list:
        if file.endswith('.xlsx') or file.endswith('.xlx'):
            excel_count += 1
            excel_name = file
    if excel_count == 0:
        input('文件夹下没有excel，按任意键退出...')
        raise Exception(0)
    if excel_count > 1:
        input('只能放一个excel，按任意键退出...')
        raise Exception(0)

    # print(excel_name)
    # raise Exception(1212)
    # ----------------------------------------------------------------------
    # print(excel_path)
    # print(img_dir)

    # 读取excel ----------------------------------------
    excel_path = os.path.join(operate_dir, excel_name)
    # print(excel_path)
    try:
        df = pd.read_excel(excel_path)
        df = df.where(df.notnull(), None)
    except Exception as e:
        print(e)
        print('文件不存在或已损坏...')
        input('按任意键退出...')
        raise Exception('123')
    # -------------------------------------------------

    # 备份原始excel表 --------------------------------------------------------------
    print('备份excel...')
    bak_dir = '题名拆分前的备份'
    file_list = os.listdir(operate_dir)
    if bak_dir not in file_list:
        os.makedirs(os.path.join(operate_dir, bak_dir))
    bak_excel_path = os.path.join(os.path.join(operate_dir, bak_dir), excel_name)
    shutil.copyfile(excel_path, bak_excel_path)
    # -----------------------------------------------------------------------------

    # --------------------------------
    all_nomatch_list = []  # 未匹配到的数据
    all_zhengtiming_list = []  # 正题名
    all_fencehao_list = []  # 分册号
    all_fenceming_list = []  # 分册名
    all_banbenbeizhu_list = []  # 版本备注
    all_banbenshuoming_list = []  # 版本说明
    all_bind_list = []  # 装帧
    all_fujian_list = []  # 附件
    all_kaiben_list = []  # 开本
    all_congshuming_list = []  # 丛书名
    all_futiming_list = []  # 副题名
    all_taozhuangshuliang_list = []  # 套装数量
    all_author_list = []  # 作者
    # --------------------------------

    for i in range(df.shape[0]):

        # 源题名
        try:
            source_title = df.loc[i, source_title_col]
        except Exception as e:
            print(e)
            print('excel中好像没有“拆分后元数据内容”这一列')
            input('按任意键退出...')
            raise Exception('123')
        print(source_title)

        if not source_title:
            all_zhengtiming_list.append(None)   # 正题名
            all_fencehao_list.append(None)  # 分册号
            all_fenceming_list.append(None)  # 分册名
            all_banbenbeizhu_list.append(None)  # 版本备注
            all_banbenshuoming_list.append(None)  # 版本说明
            all_bind_list.append(None)  # 装帧
            all_fujian_list.append(None)  # 附件
            all_kaiben_list.append(None)  # 开本
            all_congshuming_list.append(None)  # 丛书名
            all_futiming_list.append(None)  # 副题名
            all_taozhuangshuliang_list.append(None)  # 套装数量
            all_nomatch_list.append(None)  # 未匹配数据
            all_author_list.append(None)  # 作者
        else:
            source_title = str(source_title)

            # 走正常流程拆 -------------------------------------------------------------------------

            split_list = source_title.split(';')

            # 正题名提取 --------------------------
            zhengtiming_list = ReMatchFunc.zhengtiming(split_list)
            # print(zhengtiming_list)
            zhengtiming_str = ';'.join(zhengtiming_list) if zhengtiming_list else None
            all_zhengtiming_list.append(zhengtiming_str)
            # -----------------------------------

            # 作者提取 -----------------------------------
            author_list = ReMatchFunc.author(split_list)
            # print(author_list)
            author_str = ';'.join(author_list) if author_list else None
            all_author_list.append(author_str)
            # -------------------------------------------

            # 分册号提取 ------------------------------------------------------
            fencehao_list = ReMatchFunc.fencehao(split_list)
            # print(fencehao_list)
            fencehao_str = ';'.join(fencehao_list) if fencehao_list else None
            all_fencehao_list.append(fencehao_str)
            # ---------------------------------------------------------------

            # 套装数量提取 -------------------------------------------------------------------------
            taozhuangshuliang_list = ReMatchFunc.taozhuangshuliang(split_list)
            # print(banbenshuoming_list)
            taozhuangshuliang_str = ';'.join(taozhuangshuliang_list) if taozhuangshuliang_list else None
            all_taozhuangshuliang_list.append(taozhuangshuliang_str)
            # ---------------------------------------------------------------------------------

            # 分册名提取 -------------------------------------------------------------
            fenceming_list = ReMatchFunc.fenceming(split_list)
            # print(fencehao_list)

            # 将 分册号 和 套装数量 从 分册名 中剔除 ---
            new_fenceming_list = []
            for fenceming in fenceming_list:
                if fenceming not in fencehao_list and fenceming not in taozhuangshuliang_list:
                    new_fenceming_list.append(fenceming)
            fenceming_list = new_fenceming_list
            # ------------------------------------

            fenceming_str = ';'.join(fenceming_list) if fenceming_list else None
            all_fenceming_list.append(fenceming_str)
            # -----------------------------------------------------------------------

            # 版本备注提取 ----------------------------------------------------------------
            banbenbeizhu_list = ReMatchFunc.banbenbeizhu(split_list)
            # print(banbenbeizhu_list)
            banbenbeizhu_str = ';'.join(banbenbeizhu_list) if banbenbeizhu_list else None
            all_banbenbeizhu_list.append(banbenbeizhu_str)
            # ---------------------------------------------------------------------------

            # 版本说明提取 ----------------------------------------------------------------------
            banbenshuoming_list = ReMatchFunc.banbenshuoming(split_list)
            # print(banbenshuoming_list)
            banbenshuoming_str = ';'.join(banbenshuoming_list) if banbenshuoming_list else None
            all_banbenshuoming_list.append(banbenshuoming_str)
            # ---------------------------------------------------------------------------------

            # 版本说明提取 ----------------------------------------------------------------------
            bind_list = ReMatchFunc.bind(split_list)
            # print(banbenshuoming_list)
            bind_str = ';'.join(bind_list) if bind_list else None
            all_bind_list.append(bind_str)
            # ---------------------------------------------------------------------------------

            # 附件提取 -------------------------------------------------------------------------
            fujian_list = ReMatchFunc.fujian(split_list)
            # print(banbenshuoming_list)
            fujian_str = ';'.join(fujian_list) if fujian_list else None
            all_fujian_list.append(fujian_str)
            # ---------------------------------------------------------------------------------

            # 开本提取 -------------------------------------------------------------------------
            kaiben_list = ReMatchFunc.kaiben(split_list)
            # print(banbenshuoming_list)
            kaiben_str = ';'.join(kaiben_list) if kaiben_list else None
            all_kaiben_list.append(kaiben_str)
            # ---------------------------------------------------------------------------------

            # 丛书名提取 -------------------------------------------------------------------------
            congshuming_list = ReMatchFunc.congshuming(split_list)
            # print(banbenshuoming_list)
            congshuming_str = ';'.join(congshuming_list) if congshuming_list else None
            all_congshuming_list.append(congshuming_str)
            # ---------------------------------------------------------------------------------

            # 副题名提取 -------------------------------------------------------------------------
            futiming_list = ReMatchFunc.futiming(split_list)
            # print(banbenshuoming_list)
            futiming_str = ';'.join(futiming_list) if futiming_list else None
            all_futiming_list.append(futiming_str)
            # ---------------------------------------------------------------------------------
            # -------------------------------------------------------------------------------------

            # 未匹配到的数据提取 --------------------------------------------
            nomatch_list = []
            # print(zhengtiming_list, author_list, fencehao_list, fenceming_list, banbenbeizhu_list, banbenshuoming_list, bind_list, fujian_list, kaiben_list, congshuming_list, futiming_list, taozhuangshuliang_list)
            match_list = zhengtiming_list + author_list + fencehao_list + fenceming_list + banbenbeizhu_list + banbenshuoming_list + bind_list + fujian_list + kaiben_list + congshuming_list + futiming_list + taozhuangshuliang_list
            for txt in split_list:
                if txt not in match_list:
                    nomatch_list.append(txt)
            nomatch_str = ';'.join(nomatch_list) if nomatch_list else None
            all_nomatch_list.append(nomatch_str)
            # -------------------------------------------------------------

            # ------------------------------------------------------------------------------------------

            print(i, split_list)

    # 打印拆分结果 ------------------
    print('all_nomatch_list: {}'.format(all_nomatch_list))
    print('all_zhengtiming_list: {}'.format(all_zhengtiming_list))
    print('all_author_list: {}'.format(all_author_list))
    print('all_fencehao_list: {}'.format(all_fencehao_list))
    print('all_fenceming_list: {}'.format(all_fenceming_list))
    print('all_banbenbeizhu_list: {}'.format(all_banbenbeizhu_list))
    print('all_banbenshuoming_list: {}'.format(all_banbenshuoming_list))
    print('all_bind_list: {}'.format(all_bind_list))
    print('all_fujian_list: {}'.format(all_fujian_list))
    print('all_kaiben_list{}'.format(all_kaiben_list))
    print('all_congshuming_list: {}'.format(all_congshuming_list))
    print('all_futiming_list: {}'.format(all_futiming_list))
    print('all_taozhuangshuliang_list: {}'.format(all_taozhuangshuliang_list))
    # print('all_no_split_title_flag: {}'.format(all_no_split_title_flag))
    # -----------------------------

    # 保存拆分结果 ----------------------------
    df.loc[:, '[拆分]未匹配到的数据'] = all_nomatch_list
    df.loc[:, '[拆分]正题名'] = all_zhengtiming_list
    df.loc[:, '[拆分]作者'] = all_author_list
    df.loc[:, '[拆分]分册号'] = all_fencehao_list
    df.loc[:, '[拆分]分册名'] = all_fenceming_list
    df.loc[:, '[拆分]版本备注'] = all_banbenbeizhu_list
    df.loc[:, '[拆分]版本说明'] = all_banbenshuoming_list
    df.loc[:, '[拆分]装帧'] = all_bind_list
    df.loc[:, '[拆分]附资源'] = all_fujian_list
    df.loc[:, '[拆分]开本'] = all_kaiben_list
    df.loc[:, '[拆分]丛书名'] = all_congshuming_list
    df.loc[:, '[拆分]副题名'] = all_futiming_list
    df.loc[:, '[拆分]套装数量'] = all_taozhuangshuliang_list
    # df.loc[:, '[拆分]原题名未拆分标记'] = all_no_split_title_flag
    df.to_excel(excel_path, index=0)
    # ---------------------------------------


if __name__ == '__main__':
    operate_dir = r'C:\Users\cxstar46\Desktop\正则表达式题名拆分测试'
    pick_1(operate_dir)

